package com.xucy.springboot.netty.nettyhttputil;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;

import java.net.InetSocketAddress;

/**
 * @Author xucy
 * @Date 2019-06-27 15:22
 * @Description
 **/

public class NettyHttpClient {

    public void client(String ip ,int port,String uri){
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup();

        try{
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(ip, port))
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {


                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //包含编码器和解码器
                            socketChannel.pipeline().addLast(new HttpClientCodec());

                            //聚合
                            socketChannel.pipeline().addLast(new HttpObjectAggregator(1024 * 10 * 1024));

                            //解压
                            socketChannel.pipeline().addLast(new HttpContentDecompressor());

                            socketChannel.pipeline().addLast(new HttpClientHandler());
                        }
                    });

            // 发起异步连接操作
            ChannelFuture f = bootstrap.connect().sync();

            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }



    public static void main(String[] args) {
        NettyHttpClient nettyHttpClient=new NettyHttpClient();
        nettyHttpClient.client("127.0.0.1",8080,"bdmp/batchGrantCon/queryAsValInfo");
    }
}
